import cv2
import numpy as np
if __name__ == '__main__':
    # 图片输入
    image_np = cv2.imread('work1.1.jpg')
    # 模板输入
    logo = cv2.imread('work1.png')

    # x_min_l, x_max_l = 450,650
    # y_min_l, y_max_l = 120, 265
    # line_width = 2
    # cv2.rectangle(image_np, (x_min_l, y_min_l), (x_max_l, y_max_l), (0, 0, 255), line_width)

    # print(logo.shape)
    resize_logo = cv2.resize(
        logo,  # 原图
        (200, 145),  # 目标分辨率(宽高)，如果设置这个参数，x轴和y轴的缩放比例失效
        fx=0.1,  # x轴倍率
        fy=0.1,  # y轴倍率
        interpolation=cv2.INTER_LINEAR  # 插值方法
    )

    resize_logo_hsv = cv2.cvtColor(resize_logo, cv2.COLOR_BGR2HSV)
    w_min = np.array([0, 0, 221])
    w_max = np.array([180, 30, 255])
    # b_min = np.array([0, 0, 46])
    # b_max = np.array([180, 43, 250])
    mask1 = cv2.inRange(resize_logo_hsv, w_min, w_max)
    # mask2 = cv2.inRange(resize_logo_hsv, b_min, b_max)
    # mask = cv2.bitwise_or(mask1, mask2)
    for i in range(0, resize_logo.shape[0]):
        for j in range(0, resize_logo.shape[1]):
            if mask1[i, j] == 255:
                resize_logo[i, j] = 255


    gray_logo = cv2.cvtColor(resize_logo, cv2.COLOR_BGR2GRAY)

    # 二值化
    ret, mask_logo = cv2.threshold(gray_logo, 0, 255, cv2.THRESH_BINARY_INV)

    rows, cols = resize_logo.shape[:2]
    print(rows,cols)
    roi = image_np[119:119 + rows, 449:449 + cols]
    print(roi.shape)
    # image_np_bg = cv2.bitwise_and(roi, roi, mask = mask_logo)
    # dst = cv2.add(image_np_bg, resize_logo)
    # image_np[119:119 + rows, 449:449 + cols] = dst

    for i in range(0, roi.shape[0]):
        for j in range(0, roi.shape[1]):
            if mask1[i, j] != 255:
                roi[i, j] = resize_logo[i, j]


    #
    # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    # image_np_d = cv2.dilate(image_np, kernel = kernel)


    # cv2.imshow('', image_np)
    # cv2.imshow('', mask_logo)
    # # cv2.imshow('', roi)
    # cv2.imshow('', image_np_bg)
    # # cv2.imshow('', resize_logo)
    cv2.imshow('', image_np)
    # cv2.imshow('', resize_logo)
    cv2.imwrite('zuoye1.jpg', image_np)
    cv2.waitKey(0)
